package com.zeei.ems.base.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zeei.ems.base.util.BCryptUtil;
import com.zeei.ems.base.vo.UserVO;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String contentType = request.getContentType().toLowerCase();
        if (contentType.equals("application/json; charset=utf-8") ||
            contentType.equals(MediaType.APPLICATION_JSON_UTF8_VALUE) ||
            contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()) {
                UserVO loginDto = mapper.readValue(is, UserVO.class);
                String encode = BCryptUtil.encode(loginDto.getLoginpw());
                authRequest = new UsernamePasswordAuthenticationToken(
                        loginDto.getLoginname(), loginDto.getLoginpw());
            } catch (IOException e) {
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            } finally {
                setDetails(request, authRequest);
                Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest);
                return 	authenticate;
            }
        } else {
            return super.attemptAuthentication(request, response);
        }
    }
}
